<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>角色管理</title>
    <link rel="stylesheet" href="/libs/element-plus.css">
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: Arial, sans-serif;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .card-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #303133;
            border-left: 4px solid #409EFF;
            padding-left: 10px;
        }
        
        .form-row {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
            align-items: center;
        }
        
        .form-row label {
            width: 100px;
            text-align: right;
        }
        
        .form-row input, .form-row textarea {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .form-row select {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .form-row button {
            padding: 8px 20px;
            background-color: #409EFF;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .form-row button:hover {
            background-color: #66b1ff;
        }
        
        .form-row button.secondary {
            background-color: #909399;
        }
        
        .form-row button.secondary:hover {
            background-color: #a6a9ad;
        }
        
        .form-row button.success {
            background-color: #67c23a;
        }
        
        .form-row button.success:hover {
            background-color: #85ce61;
        }
        
        .form-row button.danger {
            background-color: #f56c6c;
        }
        
        .form-row button.danger:hover {
            background-color: #f78989;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        
        th, td {
            padding: 12px 10px;
            text-align: left;
            border-bottom: 1px solid #ebeef5;
        }
        
        th {
            background-color: #f5f7fa;
            font-weight: bold;
            color: #909399;
        }
        
        tr:hover {
            background-color: #f5f7fa;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: #909399;
        }
        
        .error {
            color: #f56c6c;
            padding: 10px;
            background-color: #fef0f0;
            border: 1px solid #fde2e2;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        
        .success {
            color: #67c23a;
            padding: 10px;
            background-color: #f0f9ec;
            border: 1px solid #e1f3d8;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        
        .hidden {
            display: none;
        }
        
        .user-roles {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
        }
        
        .role-tag {
            background-color: #ecf5ff;
            color: #409eff;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
        }
        
        .role-tag .remove {
            margin-left: 5px;
            cursor: pointer;
            color: #f56c6c;
        }
        
        .role-description {
            font-size: 12px;
            color: #909399;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>角色管理</h1>
        </div>
        
        <div id="message" class="hidden"></div>
        
        <div class="card">
            <div class="card-title">创建角色</div>
            <div class="form-row">
                <label>角色名称:</label>
                <input type="text" id="roleName" placeholder="请输入角色名称">
            </div>
            <div class="form-row">
                <label>角色描述:</label>
                <textarea id="roleDescription" placeholder="请输入角色描述"></textarea>
            </div>
            <div class="form-row">
                <label></label>
                <button id="createRoleBtn">创建角色</button>
            </div>
        </div>
        
        <div class="card">
            <div class="card-title">用户角色分配</div>
            <div class="form-row">
                <label>选择用户:</label>
                <select id="userSelect">
                    <option value="">请选择用户</option>
                </select>
                <label>分配角色:</label>
                <select id="roleSelect">
                    <option value="">请选择角色</option>
                </select>
                <button id="assignRoleBtn">分配角色</button>
            </div>
        </div>
        
        <div class="card">
            <div class="card-title">用户列表</div>
            <div id="usersLoading" class="loading">加载中...</div>
            <table id="usersTable" class="hidden">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>状态</th>
                        <th>角色</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="usersTableBody">
                    <!-- 用户数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
        
        <div class="card">
            <div class="card-title">角色列表</div>
            <div id="rolesLoading" class="loading">加载中...</div>
            <table id="rolesTable" class="hidden">
                <thead>
                    <tr>
                        <th>角色名称</th>
                        <th>描述</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="rolesTableBody">
                    <!-- 角色数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
    </div>

    <script src="/libs/vue.global.prod.js"></script>
    <script src="/libs/element-plus.js"></script>
    
    <script>
        // 全局变量
        let users = [];
        let roles = [];
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', async function() {
            // 绑定事件
            bindEvents();
            
            // 加载数据
            await loadData();
        });
        
        // 绑定事件
        function bindEvents() {
            document.getElementById('createRoleBtn').addEventListener('click', createRole);
            document.getElementById('assignRoleBtn').addEventListener('click', assignRole);
        }
        
        // 显示消息
        function showMessage(message, type = 'info') {
            const messageEl = document.getElementById('message');
            messageEl.textContent = message;
            messageEl.className = type;
            messageEl.classList.remove('hidden');
            
            // 3秒后自动隐藏
            setTimeout(() => {
                messageEl.classList.add('hidden');
            }, 3000);
        }
        
        // 显示错误消息
        function showError(message) {
            showMessage(message, 'error');
        }
        
        // 显示成功消息
        function showSuccess(message) {
            showMessage(message, 'success');
        }
        
        // 加载所有数据
        async function loadData() {
            try {
                await Promise.all([
                    loadUsers(),
                    loadRoles()
                ]);
                renderUsers();
                renderRoles();
                populateSelects();
            } catch (error) {
                console.error('加载数据失败:', error);
                showError('加载数据失败: ' + error.message);
            }
        }
        
        // 加载用户列表
        async function loadUsers() {
            try {
                document.getElementById('usersLoading').classList.remove('hidden');
                document.getElementById('usersTable').classList.add('hidden');
                
                const response = await fetch('/user/list', {
                    credentials: 'include'
                });
                
                if (response.status === 201) {
                    // 特别处理201状态码
                    const result = await response.json();
                    users = result.data || [];
                    
                    // 为每个用户加载角色
                    for (const user of users) {
                        try {
                            const roleResponse = await fetch(`/casbin-role/${user.username}/roles`, {
                                credentials: 'include'
                            });
                            
                            if (roleResponse.ok) {
                                const roleResult = await roleResponse.json();
                                user.roles = roleResult.data || [];
                            } else {
                                user.roles = [];
                            }
                        } catch (error) {
                            user.roles = [];
                        }
                    }
                } else if (response.ok) {
                    const result = await response.json();
                    users = result.data || [];
                    
                    // 为每个用户加载角色
                    for (const user of users) {
                        try {
                            const roleResponse = await fetch(`/casbin-role/${user.username}/roles`, {
                                credentials: 'include'
                            });
                            
                            if (roleResponse.ok) {
                                const roleResult = await roleResponse.json();
                                user.roles = roleResult.data || [];
                            } else {
                                user.roles = [];
                            }
                        } catch (error) {
                            user.roles = [];
                        }
                    }
                } else {
                    throw new Error(`加载用户列表失败，状态码: ${response.status}`);
                }
            } finally {
                document.getElementById('usersLoading').classList.add('hidden');
                document.getElementById('usersTable').classList.remove('hidden');
            }
        }
        
        // 加载角色列表
        async function loadRoles() {
            try {
                document.getElementById('rolesLoading').classList.remove('hidden');
                document.getElementById('rolesTable').classList.add('hidden');
                
                const response = await fetch('/casbin-role/list', {
                    credentials: 'include',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.status === 201) {
                    // 特别处理201状态码
                    const result = await response.json();
                    roles = result.data || [];
                } else if (response.ok) {
                    const result = await response.json();
                    roles = result.data || [];
                } else {
                    throw new Error(`加载角色列表失败，状态码: ${response.status}`);
                }
            } finally {
                document.getElementById('rolesLoading').classList.add('hidden');
                document.getElementById('rolesTable').classList.remove('hidden');
            }
        }
        
        // 渲染用户列表
        function renderUsers() {
            const tbody = document.getElementById('usersTableBody');
            tbody.innerHTML = '';
            
            users.forEach(user => {
                const row = document.createElement('tr');
                
                // 用户角色标签
                let rolesHtml = '';
                if (user.roles && user.roles.length > 0) {
                    rolesHtml = user.roles.map(role => 
                        `<span class="role-tag">${role} <span class="remove" onclick="removeRole('${user.username}', '${role}')">×</span></span>`
                    ).join(' ');
                } else {
                    rolesHtml = '<span class="role-tag">无角色</span>';
                }
                
                row.innerHTML = `
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>${user.email || '-'}</td>
                    <td>${user.status ? '启用' : '禁用'}</td>
                    <td>
                        <div class="user-roles">${rolesHtml}</div>
                    </td>
                    <td>
                        <div class="action-buttons">
                            <button class="secondary" onclick="loadUserRoles('${user.username}')">刷新角色</button>
                        </div>
                    </td>
                `;
                
                tbody.appendChild(row);
            });
        }
        
        // 渲染角色列表
        function renderRoles() {
            const tbody = document.getElementById('rolesTableBody');
            tbody.innerHTML = '';
            
            roles.forEach(role => {
                const row = document.createElement('tr');
                const createdAt = new Date(role.createdAt).toLocaleString();
                row.innerHTML = `
                    <td>${role.name}</td>
                    <td>${role.description || '-'}</td>
                    <td>${role.status ? '启用' : '禁用'}</td>
                    <td>${createdAt}</td>
                    <td>
                        <div class="action-buttons">
                            <button onclick="managePermissions('${role.name}')">菜单权限</button>
                            <button class="danger" onclick="deleteRole('${role.name}')">删除角色</button>
                        </div>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }
        
        // 填充下拉选择框
        function populateSelects() {
            // 填充用户选择框
            const userSelect = document.getElementById('userSelect');
            userSelect.innerHTML = '<option value="">请选择用户</option>';
            users.forEach(user => {
                const option = document.createElement('option');
                option.value = user.username;
                option.textContent = `${user.username} (${user.id})`;
                userSelect.appendChild(option);
            });
            
            // 填充角色选择框
            const roleSelect = document.getElementById('roleSelect');
            roleSelect.innerHTML = '<option value="">请选择角色</option>';
            roles.forEach(role => {
                const option = document.createElement('option');
                option.value = role.name;
                option.textContent = role.name;
                roleSelect.appendChild(option);
            });
        }
        
        // 创建角色
        async function createRole() {
            const roleName = document.getElementById('roleName').value.trim();
            const roleDescription = document.getElementById('roleDescription').value.trim();
            
            if (!roleName) {
                showError('请输入角色名称');
                return;
            }
            
            try {
                const response = await fetch('/casbin-role/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        roleName: roleName,
                        description: roleDescription || undefined
                    }),
                    credentials: 'include'
                });
                
                if (response.status === 201) {
                    // 特别处理201状态码
                    showSuccess('角色创建成功');
                    document.getElementById('roleName').value = '';
                    document.getElementById('roleDescription').value = '';
                    await loadData();
                } else if (response.ok) {
                    const result = await response.json();
                    if (result) {
                        showSuccess('角色创建成功');
                        document.getElementById('roleName').value = '';
                        document.getElementById('roleDescription').value = '';
                        await loadData();
                    } else {
                        throw new Error('角色创建失败: 服务器返回false');
                    }
                } else {
                    throw new Error(`角色创建失败，状态码: ${response.status}`);
                }
            } catch (error) {
                console.error('创建角色失败:', error);
                showError('创建角色失败: ' + error.message);
            }
        }
        
        // 分配角色
        async function assignRole() {
            const username = document.getElementById('userSelect').value;
            const roleName = document.getElementById('roleSelect').value;
            
            if (!username) {
                showError('请选择用户');
                return;
            }
            
            if (!roleName) {
                showError('请选择角色');
                return;
            }
            
            try {
                const response = await fetch(`/casbin-role/${username}/assign`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ roleName: roleName }),
                    credentials: 'include'
                });
                
                if (response.status === 201) {
                    // 特别处理201状态码
                    showSuccess(`成功为用户 ${username} 分配角色 ${roleName}`);
                    // 清空选择框
                    document.getElementById('userSelect').value = '';
                    document.getElementById('roleSelect').value = '';
                    await loadData();
                } else if (response.ok) {
                    const result = await response.json();
                    if (result) {
                        showSuccess(`成功为用户 ${username} 分配角色 ${roleName}`);
                        // 清空选择框
                        document.getElementById('userSelect').value = '';
                        document.getElementById('roleSelect').value = '';
                        await loadData();
                    } else {
                        throw new Error('角色分配失败: 服务器返回false');
                    }
                } else {
                    throw new Error(`角色分配失败，状态码: ${response.status}`);
                }
            } catch (error) {
                console.error('分配角色失败:', error);
                showError('分配角色失败: ' + error.message);
            }
        }
        
        // 移除角色
        async function removeRole(username, roleName) {
            if (!confirm(`确定要移除用户 ${username} 的角色 ${roleName} 吗？`)) {
                return;
            }
            
            try {
                const response = await fetch(`/casbin-role/${username}/remove`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ roleName: roleName }),
                    credentials: 'include'
                });
                
                if (response.status === 201) {
                    // 特别处理201状态码
                    showSuccess(`成功移除用户 ${username} 的角色 ${roleName}`);
                    await loadData();
                } else if (response.ok) {
                    const result = await response.json();
                    if (result) {
                        showSuccess(`成功移除用户 ${username} 的角色 ${roleName}`);
                        await loadData();
                    } else {
                        throw new Error('角色移除失败: 服务器返回false');
                    }
                } else {
                    throw new Error(`角色移除失败，状态码: ${response.status}`);
                }
            } catch (error) {
                console.error('移除角色失败:', error);
                showError('移除角色失败: ' + error.message);
            }
        }
        
        // 删除角色
        async function deleteRole(roleName) {
            if (!confirm(`确定要删除角色 ${roleName} 吗？这将移除所有用户对该角色的关联。`)) {
                return;
            }
            
            try {
                const response = await fetch(`/casbin-role/${roleName}`, {
                    method: 'DELETE',
                    credentials: 'include'
                });
                
                if (response.status === 201) {
                    // 特别处理201状态码
                    showSuccess(`成功删除角色 ${roleName}`);
                    await loadData();
                } else if (response.ok) {
                    const result = await response.json();
                    if (result) {
                        showSuccess(`成功删除角色 ${roleName}`);
                        await loadData();
                    } else {
                        throw new Error('角色删除失败: 服务器返回false');
                    }
                } else {
                    throw new Error(`角色删除失败，状态码: ${response.status}`);
                }
            } catch (error) {
                console.error('删除角色失败:', error);
                showError('删除角色失败: ' + error.message);
            }
        }
        
        // 加载用户角色（刷新）
        async function loadUserRoles(username) {
            try {
                const response = await fetch(`/casbin-role/${username}/roles`, {
                    credentials: 'include'
                });
                
                if (response.status === 201) {
                    // 特别处理201状态码
                    const result = await response.json();
                    const userRoles = result.data || [];
                    // 更新用户的角色信息
                    const user = users.find(u => u.username === username);
                    if (user) {
                        user.roles = userRoles;
                        renderUsers();
                        showSuccess(`已刷新用户 ${username} 的角色信息`);
                    }
                } else if (response.ok) {
                    const result = await response.json();
                    const userRoles = result.data || [];
                    // 更新用户的角色信息
                    const user = users.find(u => u.username === username);
                    if (user) {
                        user.roles = userRoles;
                        renderUsers();
                        showSuccess(`已刷新用户 ${username} 的角色信息`);
                    }
                } else {
                    throw new Error(`加载用户角色失败，状态码: ${response.status}`);
                }
            } catch (error) {
                console.error('加载用户角色失败:', error);
                showError('加载用户角色失败: ' + error.message);
            }
        }
        
        // 管理角色权限
        async function managePermissions(roleName) {
            // 跳转到权限管理页面
            window.location.href = `/role/permissions?name=${roleName}`;
        }
    </script>
</body>
</html>